package com.lon.over.presenter.impl;

import com.lon.over.model.Api;
import com.lon.over.model.domain.HomePagerContent;
import com.lon.over.presenter.ICategoryPresenter;
import com.lon.over.utils.LogUtils;
import com.lon.over.utils.RetrofitManager;
import com.lon.over.utils.UrlUtils;
import com.lon.over.view.ICategoryPagerCallback;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * author: ctl | 陈泰龙
 * 创建时间: 2022/4/24
 * Describe:
 */
public class CategoryPresenterImpl implements ICategoryPresenter {

    private Map<Integer, Integer> pagerInfo = new HashMap<>();

    private static final int DEFAULT_PAGE = 1;

    private List<ICategoryPagerCallback> mCallback = new ArrayList<>();
    private Integer mCurrentPage;


    private static ICategoryPresenter sInstance = null;
    /**
     * 获取对象的方法：获取单例对象（懒汉式）
     *
     * @return
     */

    public static ICategoryPresenter getInstance() {
        if (sInstance == null) {
            synchronized (CategoryPresenterImpl.class) {
                if (sInstance == null) {
                    sInstance = new CategoryPresenterImpl();
                }
            }
        }
        return sInstance;
    }

    private CategoryPresenterImpl() {
    }

    @Override
    public void getContentByCategoryId(int categoryId) {
        for (ICategoryPagerCallback callback : mCallback) {
            if (callback.getCateGoryId() == categoryId) {
                callback.onLading();
            }
        }
        // 根据id 获取内容
        Integer targetPage = pagerInfo.get(categoryId);
        if (targetPage == null) {
            targetPage = DEFAULT_PAGE;
            pagerInfo.put(categoryId, targetPage);
        }
        Call<HomePagerContent> task = createTask(categoryId, targetPage);
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                int code = response.code();
                LogUtils.d(CategoryPresenterImpl.this, "code is -- > " + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent homePagerContent = response.body();
                    handleHomePagerContentResult(homePagerContent, categoryId);
                } else {
                    handleNetworkError(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                handleNetworkError(categoryId);
            }
        });
    }

    private Call<HomePagerContent> createTask(int categoryId, Integer targetPage) {
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        String url = UrlUtils.createHomePagerUrl(categoryId, targetPage);
        return api.getHomePagerContent(url);
    }


    private void handleNetworkError(int categoryId) {
        for (ICategoryPagerCallback callback : mCallback) {
            if (callback.getCateGoryId() == categoryId) {
                callback.onError();
            }
        }
    }

    private void handleHomePagerContentResult(HomePagerContent pagerContent, int categoryId) {
        // 通知UI更新数据
        List<HomePagerContent.DataBean> data = pagerContent.getData();
        for (ICategoryPagerCallback callback : mCallback) {
            if (callback.getCateGoryId() == categoryId) {
                if (pagerContent == null || data.size() == 0) {
                    callback.onEmpty();
                } else {
                    List<HomePagerContent.DataBean> looperData = data.subList(data.size() - 5, data.size());
                    callback.onLooperListLoaded(looperData);
                    callback.onContentLoad(data);
                }
            }
        }
    }

    @Override
    public void loadMore(int categoryId) {
        //实现加载更多内容
        //拿到当前页面
        mCurrentPage = pagerInfo.get(categoryId);
        if (mCurrentPage == null) {
            mCurrentPage = 1;
        }
        //页数增加
        mCurrentPage++;
        //加载数据
        Call<HomePagerContent> task = createTask(categoryId, mCurrentPage);
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent result = response.body();
                    handleLoaderResult(result, categoryId);
                } else {
                    handleLoaderMoreError(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                handleLoaderMoreError(categoryId);
            }
        });
    }

    //成功时处理事件
    private void handleLoaderResult(HomePagerContent result, int categoryId) {
        for (ICategoryPagerCallback callback : mCallback) {
            if (callback.getCateGoryId() == categoryId) {
                if (result == null || result.getData().size() == 0) {
                    callback.onLoaderMoreEmpty();
                } else {
                    callback.onLoaderMoreLoaded(result.getData());
                }
            }
        }
    }

    //加载失败时处理事件
    private void handleLoaderMoreError(int categoryId) {
        mCurrentPage--;
        pagerInfo.put(categoryId, mCurrentPage);
        for (ICategoryPagerCallback callback : mCallback) {
            if (callback.getCateGoryId() == categoryId) {
                callback.onLoaderMoreError();
            }
        }
    }

    @Override
    public void reload(int categoryId) {

    }

    @Override
    public void registerViewCallback(ICategoryPagerCallback callback) {
        if (!mCallback.contains(callback)) {
            mCallback.add(callback);
        }
    }

    @Override
    public void unregisterViewCallback(ICategoryPagerCallback callback) {
        mCallback.remove(callback);
    }
}
